/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.evolve.webbot.file;
import  java.io.File;
import  java.io.InputStream;
import  java.io.OutputStream;
import  java.io.FileInputStream;
import  java.io.FileOutputStream;
import  java.io.BufferedInputStream;
import  java.io.BufferedOutputStream;
import  java.io.IOException;
import  java.util.zip.*;
import  java.util.zip.ZipException;
import  java.util.Date;
import  java.util.Enumeration;
import  java.util.List;
import  java.util.ArrayList;
import  java.util.logging.Level;
import  java.util.logging.Logger;
import  java.text.SimpleDateFormat;
import  org.jdom.Document;
import  org.jdom.Element;
import  org.jdom.JDOMException;
import  org.jdom.input.SAXBuilder;

import  com.evolve.webbot.bean.SearsBean;
import  com.evolve.webbot.bean.SearsInventarioBean;
import java.io.*;

/**
*
* @author shunmuga
*/

public class XmlFileSears
{
    final   int BUFFER = 2048;
    private String filePath;

    public XmlFileSears(){}
    
    public XmlFileSears(String filePath)
    {
        this.filePath=filePath;
    }

    public String unZipXmlFile(String zipXmlFile)
    {
        String unzipFilePath = null;
        
        try {
                BufferedOutputStream dest = null;
                FileInputStream      fis  = new FileInputStream(zipXmlFile);
                
                ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
                ZipEntry entry;
         
                while((entry = zis.getNextEntry()) != null)
                {
                    //log.info("Extracting: " +entry);

                    int count;
                    byte data[] = new byte[BUFFER];

                    unzipFilePath = zipXmlFile.substring(0,zipXmlFile.indexOf("Sears"))+
                                                         File.separator+entry.getName();
                    
                    FileOutputStream fos = new FileOutputStream(unzipFilePath);

                    dest = new BufferedOutputStream(fos, BUFFER);
                    
                    while ((count = zis.read(data, 0, BUFFER))!= -1)
                    {
                        dest.write(data, 0, count);
                    }

                    dest.flush();
                    dest.close();
                }

                zis.close();
                
            } catch(Exception e) {e.printStackTrace();}
        
        return unzipFilePath;
    }

    public ArrayList<SearsBean> getSearsRecords(String unZipXlsFilePath)
    throws JDOMException, IOException
    {

        ArrayList<SearsBean> searsRecordList = new ArrayList<SearsBean>();

        SAXBuilder builder = new SAXBuilder();
        Document document  = (Document) builder.build(new File(unZipXlsFilePath));
        Element  root      = document.getRootElement();
        List totalRow      = root.getChildren("VTAS");

        for (int i = 0; i < totalRow.size(); i++)
        {
            Element frameWork = (Element) totalRow.get(i);
            SearsBean searsRecord = new SearsBean();

            searsRecord.setTienda(frameWork.getAttribute("TIENDA").getValue());
            searsRecord.setProveedor(frameWork.getAttribute("PROVEEDOR").getValue());
            searsRecord.setCategoria(frameWork.getAttribute("CATEGORIA").getValue());
            searsRecord.setDivision(frameWork.getAttribute("DIVISION").getValue());
            searsRecord.setSku(frameWork.getAttribute("SKU").getValue());
            searsRecord.setEan(frameWork.getAttribute("EAN").getValue());
            searsRecord.setEanRelacionado(frameWork.getAttribute("EAN_RELACIONADO").getValue());
            searsRecord.setEanArt(frameWork.getAttribute("ENL_ART").getValue());
            searsRecord.setDesArt(frameWork.getAttribute("DES_ART").getValue());
            searsRecord.setStsArt(frameWork.getAttribute("STS_ART").getValue());
            searsRecord.setTalla(frameWork.getAttribute("TALLA").getValue());
            searsRecord.setColor(frameWork.getAttribute("COLOR").getValue());
            searsRecord.setMarca(frameWork.getAttribute("MARCA").getValue());
            searsRecord.setEstilo(frameWork.getAttribute("ESTILO").getValue());
            
            searsRecord.setVtaDiaPzas(frameWork.getAttribute("VTA_DIA_Pzas").getValue());
            searsRecord.setVtaDiaImpte(frameWork.getAttribute("VTA_DIA_Impte").getValue());
            
            searsRecord.setVtaMesPzas(frameWork.getAttribute("VTA_MES_Pzas").getValue());
            searsRecord.setVtaMesImpte(frameWork.getAttribute("VTA_MES_Impte").getValue());
            searsRecord.setFechaAlta(frameWork.getAttribute("FECHA_ALTA").getValue());
            searsRecord.setFechaUltCompra(frameWork.getAttribute("FECHA_ULT_COMPRA").getValue());
            searsRecord.setCostoUni(frameWork.getAttribute("COSTO_UNI").getValue());
            searsRecord.setVentaUni(frameWork.getAttribute("VENTA_UNI").getValue());
            searsRecord.setCodFam(frameWork.getAttribute("COD_FAM").getValue());
            searsRecord.setColeccion(frameWork.getAttribute("COLECCION").getValue());
            searsRecord.setProveedorNombre(frameWork.getAttribute("PROVEEDOR_NOMBRE").getValue());
            searsRecord.setTemporada(frameWork.getAttribute("TEMPORADA").getValue());

            System.out.println(searsRecord.toString());

            searsRecordList.add(searsRecord);
        }

        return searsRecordList;
    }
    
    public ArrayList<SearsBean> getSearsInternacionalRecords(String unZipXlsFilePath)
    throws JDOMException, IOException
    {

        ArrayList<SearsBean> searsRecordList = new ArrayList<SearsBean>();

        SAXBuilder builder = new SAXBuilder();
        Document document  = (Document) builder.build(new File(unZipXlsFilePath));
        Element  root      = document.getRootElement();
        List totalRow      = root.getChildren("VTAS");

        for (int i = 0; i < totalRow.size(); i++)
        {
            Element frameWork = (Element) totalRow.get(i);
            SearsBean searsRecord = new SearsBean();

            searsRecord.setTienda(frameWork.getAttribute("TIENDA").getValue());
            searsRecord.setProveedor(frameWork.getAttribute("PROVEEDOR").getValue());
            searsRecord.setCategoria(frameWork.getAttribute("CATEGORIA").getValue());
            searsRecord.setDivision(frameWork.getAttribute("DIVISION").getValue());
            searsRecord.setSku(frameWork.getAttribute("SKU").getValue());
            searsRecord.setEan(frameWork.getAttribute("EAN").getValue());
            searsRecord.setEanRelacionado(frameWork.getAttribute("EAN_RELACIONADO").getValue());
            searsRecord.setEanArt(frameWork.getAttribute("ENL_ART").getValue());
            searsRecord.setDesArt(frameWork.getAttribute("DES_ART").getValue());
            searsRecord.setStsArt(frameWork.getAttribute("STS_ART").getValue());
            searsRecord.setTalla(frameWork.getAttribute("TALLA").getValue());
            searsRecord.setColor(frameWork.getAttribute("COLOR").getValue());
            searsRecord.setMarca(frameWork.getAttribute("MARCA").getValue());
            searsRecord.setEstilo(frameWork.getAttribute("ESTILO").getValue());
            
            searsRecord.setVtaDiaPzas(frameWork.getAttribute("VTA_DIA_Pzas").getValue());
            searsRecord.setVtaDiaImpte(frameWork.getAttribute("VTA_DIA_Impte").getValue());
            
            searsRecord.setVtaMesPzas(frameWork.getAttribute("VTA_MES_Pzas").getValue());
            searsRecord.setVtaMesImpte(frameWork.getAttribute("VTA_MES_Impte").getValue());
            searsRecord.setFechaAlta(frameWork.getAttribute("FECHA_ALTA").getValue());
            searsRecord.setFechaUltCompra(frameWork.getAttribute("FECHA_ULT_COMPRA").getValue());
            searsRecord.setCostoUni(frameWork.getAttribute("COSTO_UNI").getValue());
            searsRecord.setVentaUni(frameWork.getAttribute("VENTA_UNI").getValue());
            searsRecord.setCodFam(frameWork.getAttribute("COD_FAM").getValue());
            searsRecord.setColeccion(frameWork.getAttribute("COLECCION").getValue());
            searsRecord.setProveedorNombre(frameWork.getAttribute("PROVEEDOR_NOMBRE").getValue());
            searsRecord.setTemporada(frameWork.getAttribute("TEMPORADA").getValue());

            System.out.println(searsRecord.toString());

            searsRecordList.add(searsRecord);
        }

        return searsRecordList;
    } 
    
    public ArrayList<SearsInventarioBean> getSearsInventarioRecords(String unZipXlsFilePath)
    throws JDOMException, IOException
    {

        ArrayList<SearsInventarioBean> searsRecordList = new ArrayList<SearsInventarioBean>();

        SAXBuilder builder = new SAXBuilder();
        Document document  = (Document) builder.build(new File(unZipXlsFilePath));
        Element  root      = document.getRootElement();
        List totalRow      = root.getChildren("row");

        for (int i = 0; i < totalRow.size(); i++)
        {
            Element frameWork = (Element) totalRow.get(i);
            SearsInventarioBean searsRecord = new SearsInventarioBean();

            searsRecord.setImporteOrden(frameWork.getAttribute("IMPTE_ON_ORDER").getValue());
            searsRecord.setPiezasOrden(frameWork.getAttribute("PZAS_ON_ORDER").getValue());
            searsRecord.setDiasCob(frameWork.getAttribute("DIAS_COB").getValue());
            searsRecord.setTemporada(frameWork.getAttribute("TEMPORADA").getValue());
            searsRecord.setColeccion(frameWork.getAttribute("COLECCION").getValue());
            searsRecord.setCodFam(frameWork.getAttribute("COD_FAM").getValue());
            searsRecord.setVentaUni(frameWork.getAttribute("VENTA_UNI").getValue());
            searsRecord.setCostoUni(frameWork.getAttribute("COSTO_UNI").getValue());            
            searsRecord.setFechaUltCompra(frameWork.getAttribute("FECHA_ULT_COMPRA").getValue());
            searsRecord.setFechaAlta(frameWork.getAttribute("FECHA_ALTA").getValue());
            searsRecord.setEstilo(frameWork.getAttribute("ESTILO").getValue());            
            searsRecord.setMarca(frameWork.getAttribute("MARCA").getValue());            
            searsRecord.setColor(frameWork.getAttribute("COLOR").getValue());
            searsRecord.setTalla(frameWork.getAttribute("TALLA").getValue());
            searsRecord.setInvtVenta(frameWork.getAttribute("INVT_VENTA").getValue());
            searsRecord.setInvtCosto(frameWork.getAttribute("INVT_COSTO").getValue());
            searsRecord.setInvtPiezas(frameWork.getAttribute("INVT_PIEZAS").getValue());
            searsRecord.setStsArt(frameWork.getAttribute("STS_ART").getValue());
            searsRecord.setDesArt(frameWork.getAttribute("DES_ART").getValue());
            searsRecord.setEnlArt(frameWork.getAttribute("ENL_ART").getValue());
            searsRecord.setEan(frameWork.getAttribute("EAN").getValue());
            searsRecord.setEanRelacionado(frameWork.getAttribute("EAN_RELACIONADO").getValue());
            searsRecord.setSku(frameWork.getAttribute("SKU").getValue());   
            searsRecord.setDivision(frameWork.getAttribute("DIVISION").getValue());  
            searsRecord.setCategoria(frameWork.getAttribute("CATEGORIA").getValue());
            searsRecord.setProveedor(frameWork.getAttribute("PROVEEDOR").getValue());
            searsRecord.setProveedorNombre(frameWork.getAttribute("PROVEEDOR_NOMBRE").getValue());            
            searsRecord.setTienda(frameWork.getAttribute("TIENDA").getValue());
            searsRecord.setEmpresa(frameWork.getAttribute("EMPRESA").getValue());
            System.out.println(searsRecord);
            searsRecordList.add(searsRecord);
        }

        return searsRecordList;
    }   
    
    public void writeSearsDataFile(ArrayList<SearsBean> searsRecordList,String path,String strFecDownload,int opt)
    {
        Date   date    = new Date();
        String strFile ="";
        String sysDate = "";
        SimpleDateFormat sdf01 = new SimpleDateFormat("dd-MM-yyyy");
        
        sysDate = sdf01.format(date);
        
        if(opt == 1){
            strFile = "DATA_";
        }else if(opt == 2){
            strFile = "DATA_INTERNACIONAL_";
        }
        
        try {
               path = path.replace(".xml",".txt");
               path = path.replace("VTA_MES_"+sysDate,strFile+strFecDownload);
               
               FileWriter  outFile = new FileWriter(path);
               PrintWriter out     = new PrintWriter(outFile);
              
               for(int i=0;i<searsRecordList.size();i++)
               {
                 out.println(searsRecordList.get(i).toString());
               }
              
               out.close();
               
            } catch (IOException e){e.printStackTrace();}
    } 
    
    public void writeSearsInventarioDataFile(ArrayList<SearsInventarioBean> searsRecordList,String path,String strFecDownload,int opt)
    {
        Date   date    = new Date();
        String sysDate = "";
        String strFile ="";
        SimpleDateFormat sdf01 = new SimpleDateFormat("dd-MM-yyyy");
        
        sysDate = sdf01.format(date);
        
        if(opt == 1){
            strFile = "DATA_INVENTARIO_";
        }else if(opt == 2){
            strFile = "DATA_INVENTARIO_INTERNACIONAL_";
        }        
        
        try {
               path = path.replace(".xml",".txt");
               path = path.replace("INV_ROW_"+sysDate,strFile+strFecDownload);
               
               FileWriter  outFile = new FileWriter(path);
               PrintWriter out     = new PrintWriter(outFile);
              
               for(int i=0;i<searsRecordList.size();i++)
               {
                 out.println(searsRecordList.get(i).toString());
               }
              
               out.close();
               
            } catch (IOException e){e.printStackTrace();}
    }     
    
    public static void main(String args[]){
        XmlFileSears xfs = new XmlFileSears(); 
        xfs.unZipXmlFile("C:\\Users\\DarthAE\\Documents\\proyectos\\EvolveInteractive\\EvolveMainWebBot\\evolve-webbot\\sears-webbot\\sears-files\\SearsInternacional-vyc-30102013-084840.zip");
    }    
}